import WXAD, { RewardADReturn } from "../../../StartAb/WXAd";
import WXRealLogUtil from "../../../StartAb/WXRealLogUtil";
import EventCenter from "../../TFrame/script/helper/EventCenter";
import EventNames from "../EventNames";
import FireBaseAPI from "../FireBaseAPI";
import StatusProperties, { RewardType } from "../game/StatusProperties";
import NativeCaller from "../NativeCaller";
import { ActionType } from "../net/Enum";
import ServiceLogic from "../net/ServerLogic";
import CoinSystem from "../system/CoinSystem";
import TurnTableSystem, { TurnRewardItem } from "../system/TurnTableSystem";
import ToastHelper from "../ui/ToastHelper";

const { ccclass, property } = cc._decorator;

@ccclass
export default class TurnTable extends cc.Component {

    @property(cc.Node)
    turnNode: cc.Node = null;

    @property(cc.Node)
    coinTextRoot: cc.Node = null;

    @property(cc.Button)
    spinButton: cc.Button = null;

    @property(cc.Button)
    closeButton: cc.Button = null;

    @property(cc.Label)
    timesNumLabel: cc.Label = null;

    @property({ type: cc.Label, displayName: "中奖倍数提示" })
    rewardTimesLabel: cc.Label = null;

    @property(cc.Node)
    videoFlagNode: cc.Node = null

    @property(cc.Node)
    timerNode: cc.Node = null;

    _turnRewardItem: TurnRewardItem = null;

    static showing = false
    public static show() {
        if (TurnTable.showing)
            return
        TurnTable.showing = true
        cc.assetManager.getBundle("GameAb").load("prefab/turntable", cc.Prefab, ((err: Error, pf: cc.Prefab) => {
            if (err) {
                TurnTable.showing = false
                return console.log(err.message);
            }
            let dialog = cc.instantiate(pf);
            dialog.parent = cc.Canvas.instance.node;
        }))
    }

    protected onEnable(): void {
        WXAD.instance.showBanner();
    }

    protected onDisable(): void {
        TurnTable.showing = false
        WXAD.instance.hideBanner();
    }

    start() {
        this.updateCoinText();
        this.updateLeftTimesText();
        this.updateRewardTimesText();
        this.updateVideoFlag();
        this.lightAni(1.0)
        WXRealLogUtil.info("进转盘")
        EventCenter.on(EventNames.NewDaysEvent, this.newDay, this);

        if (TurnTableSystem.isNoBlood()) {
            this.spinButton.interactable = false;
            this.rewardTimesLabel.node.parent.active = false;
            this.timerNode.active = true
        }

        EventCenter.on(EventNames.RewardedSuccess, () => {
            if (StatusProperties.rewardType == RewardType.ReqTurnTable) {
                
            }
        }, this)
    }

    updateCoinText() {
        for (let i = 0; i < TurnTableSystem.rewardArray.length; ++i) {
            let n = this.coinTextRoot.getChildByName(i.toString());
            if (n) {
                n.getComponent(cc.Label).string = TurnTableSystem.rewardArray[i].toString();
            }
        }
    }

    //剩余次数
    updateLeftTimesText() {
        this.timesNumLabel.string = TurnTableSystem.currentTurnedTimes.toString() + "/" + TurnTableSystem.maxTimesPerDay.toString();
    }
    updateRewardTimesText() {
        let times = Math.min(TurnTableSystem.maxTimesPerDay, TurnTableSystem.currentTurnedTimes + 1)
        this.rewardTimesLabel.string = "x" + times.toString();
        cc.tween(this.rewardTimesLabel.node).to(0.25, { scale: 1.3 }).to(0.2, { scale: 1.0 }).start()
    }
    updateVideoFlag() {
        this.videoFlagNode.active = (TurnTableSystem.currentTurnedTimes > -1)
    }

    lightAni(duration: number) {
        let panNode = this.node.getChildByName("pan");
        for (let i = 0; i < 6; ++i) {
            let light = panNode.getChildByName("light_yel_" + i.toString())
            let shine = light.getChildByName("shine");
            cc.Tween.stopAllByTarget(shine);
            shine.opacity = 0;
            cc.tween(shine).repeatForever(cc.tween().blink(duration, 1)).start();
        }
        for (let i = 0; i < 5; ++i) {
            let light = panNode.getChildByName("light_pink_" + i.toString())
            let shine = light.getChildByName("shine");
            cc.Tween.stopAllByTarget(shine);
            shine.opacity = 0;
            cc.tween(shine).delay(duration * 0.5).repeat(100000, cc.tween().blink(duration, 1)).start();
        }
    }

    isRolling = false;
    spinClick() {
        if (TurnTableSystem.currentTurnedTimes > -1) {
            StatusProperties.rewardType = RewardType.ReqTurnTable;
            // ServiceLogic.action(ActionType.ActionTurnTableAd, { "beiz": TurnTableSystem.currentTurnedTimes + 1 })
            WXAD.instance.showReward((code: number) => {
                // console.log("视频广告回调结果:", code)
                switch(code) {
                    case RewardADReturn.PlayRewarded:
                        this.didStartTurn();
                        WXRealLogUtil.info(`转盘领取成功`)
                        break
                    case RewardADReturn.NoAd:
                        ToastHelper.show("广告未准备好,请稍后重试.")
                        WXRealLogUtil.info(`转盘领取失败无广告`)
                        break
                    case RewardADReturn.PlayNotEnd:
                        ToastHelper.show("要观看完广告才能转动转盘哟.")
                        WXRealLogUtil.info(`转盘领取失败未看完`)
                        break
                }

            })
        } else {
            // ServiceLogic.action(ActionType.ActionTurnTableFree, { "beiz": 1 })
            this.didStartTurn();
        }
    }

    didStartTurn() {
        this._turnRewardItem = TurnTableSystem.spin();
        this.spinButton.interactable = false;
        this.closeButton.interactable = false;
        this.isRolling = true;
        cc.tween(this.turnNode)
            .by(5, { angle: 3600 + this._turnRewardItem.degree - this.turnNode.angle % 360 }, { easing: "quadInOut" })
            .call(() => {
                this.spinDone();
            })
            .start();
    }

    spinDone() {
        this.isRolling = false;
        this.lightAni(0.35)
        EventCenter.emit(EventNames.FlyGetCoinEvent, this._turnRewardItem.coin, this.node.convertToWorldSpaceAR(cc.Vec2.ZERO));
        EventCenter.emit(EventNames.TurnTableSpinDone)
        CoinSystem.addCoin(this._turnRewardItem.coin);
        this.updateLeftTimesText();
        if (TurnTableSystem.isNoBlood() == false) {
            this.spinButton.interactable = true;
            this.updateRewardTimesText();
            this.updateVideoFlag()
        } else {
            this.rewardTimesLabel.node.parent.active = false;
            this.timerNode.active = true
        }
        this.closeButton.interactable = true;
        // FireBaseAPI.logEvent("Event_TurnTable", {"reward":this._turnRewardItem.coin, "times":TurnTableSystem.currentTurnedTimes, "coinhave":CoinSystem.coinInMomory})
        ServiceLogic.action(ActionType.ActionCoinChanged, { "coinhave": CoinSystem.coinInMomory, "beiz": this._turnRewardItem.coin })
    }

    newDay() {
        if (this.isRolling == false) {
            this.updateLeftTimesText();
            this.spinButton.interactable = true;
            this.updateRewardTimesText();
            this.updateVideoFlag()
        }
    }

    close() {
        this.node.destroy();
    }
}
